<template>
  <ElDialog v-model="dialogVisible" title="质检记录" width="60%" :before-close="handleClose">
    <div class="dialog-content">
      <!-- 质检记录列表 -->
      <Table :data="qualityRecords" :columns="columns" />
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <ElButton @click="dialogVisible = false" type="primary">关闭</ElButton>
      </span>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElDialog, ElButton, ElMessage } from 'element-plus'
import { Table, TableColumn } from '@/components/Table'
import { h } from 'vue'

// 定义props
const props = defineProps<Props>()
interface Props {
  visible: boolean
  selectedOrders?: any[]
  qualityRecords?: any[]
}

// 定义emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'update-records': [value: any[]]
}>()

// 计算属性：控制弹窗显示
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 质检记录数据
const qualityRecords = ref<any[]>([])

// 监听props变化
watch(() => props.qualityRecords, (newRecords) => {
  if (newRecords) {
    qualityRecords.value = newRecords
  }
}, { immediate: true })

// 表格列配置
const columns = reactive<TableColumn[]>([
  {
    field: 'inspectionDate',
    label: '质检日期',
    minWidth: 120
  },
  {
    field: 'documentName',
    label: '质检文档名称',
    minWidth: 200
  },
  {
    field: 'operation',
    label: '操作',
    fixed: 'right' as const,
    width: 100,
    slots: {
      default: ({ row }: { row: any }) => {
        return [
          h(
            ElButton,
            {
              type: 'primary',
              link: true,
              onClick: () => handleDownload(row)
            },
            () => '下载'
          )
        ]
      }
    }
  }
])

const handleClose = () => {
  dialogVisible.value = false
}

const handleDownload = async (row: any) => {
  try {
    if (row.content) {
      // 将markdown转换为Word文档并下载
      await convertMarkdownToWord(row.content, row.documentName)
      ElMessage.success('Word文档下载成功')
    } else {
      ElMessage.warning('该记录缺少下载内容')
    }
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败，请重试')
  }
}

// 将markdown转换为Word文档
const convertMarkdownToWord = async (markdownContent: string, filename: string) => {
  try {
    // 解析markdown内容
    const sections = parseMarkdownContent(markdownContent)
    
    // 生成Word文档的HTML内容
    const wordHtml = generateWordHtml(sections)
    
    // 创建包含样式的完整HTML文档
    const fullHtml = `
      <!DOCTYPE html>
      <html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'>
      <head>
        <meta charset="utf-8">
        <title>${filename}</title>
        <!--[if gte mso 9]>
        <xml>
          <w:WordDocument>
            <w:View>Print</w:View>
            <w:Zoom>90</w:Zoom>
            <w:DoNotPromptForConvert/>
            <w:DoNotShowRevisions/>
            <w:DoNotPrintRevisions/>
            <w:DisplayHorizontalDrawingGridEvery>0</w:DisplayHorizontalDrawingGridEvery>
            <w:DisplayVerticalDrawingGridEvery>2</w:DisplayVerticalDrawingGridEvery>
            <w:UseMarginsForDrawingGridOrigin/>
            <w:ValidateAgainstSchemas/>
            <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid>
            <w:IgnoreMixedContent>false</w:IgnoreMixedContent>
            <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText>
            <w:Compatibility>
              <w:BreakWrappedTables/>
              <w:SnapToGridInCell/>
              <w:WrapTextWithPunct/>
              <w:UseAsianBreakRules/>
              <w:DontGrowAutofit/>
            </w:Compatibility>
          </w:WordDocument>
        </xml>
        <![endif]-->
        <style>
          body {
            font-family: 'Microsoft YaHei', 'SimSun', Arial, sans-serif;
            font-size: 12pt;
            line-height: 1.5;
            margin: 2.54cm;
            color: #000000;
          }
          h1 {
            font-size: 18pt;
            font-weight: bold;
            text-align: center;
            margin: 20pt 0 15pt 0;
            color: #000000;
            border-bottom: none;
            padding-bottom: 5pt;
          }
          h2 {
            font-size: 14pt;
            font-weight: bold;
            margin: 15pt 0 10pt 0;
            color: #000000;
            border-bottom: none;
            padding-bottom: 3pt;
          }
          h3 {
            font-size: 12pt;
            font-weight: bold;
            margin: 12pt 0 8pt 0;
            color: #000000;
          }
          p {
            margin: 6pt 0;
            text-align: left;
            font-size: 11pt;
          }
          table {
            border-collapse: collapse;
            width: 100%;
            margin: 10pt 0;
            font-size: 10pt;
          }
          th, td {
            border: 1pt solid #000000;
            padding: 6pt;
            text-align: left;
            vertical-align: middle;
          }
          th {
            background-color: #f0f0f0;
            font-weight: bold;
            text-align: center;
          }
          .highlight {
            background-color: #ffff00;
            font-weight: bold;
          }
          .section {
            margin-bottom: 15pt;
          }
          .page-break {
            page-break-before: always;
          }
          strong {
            font-weight: bold;
            color: #000000;
          }
          .two-column {
            width: 100%;
            overflow: hidden;
          }
          .left-column {
            float: left;
            width: 50%;
            padding-right: 20px;
            box-sizing: border-box;
          }
          .right-column {
            float: right;
            width: 50%;
            padding-left: 20px;
            box-sizing: border-box;
          }
          .clear-float {
            clear: both;
          }
        </style>
      </head>
      <body>
        ${wordHtml}
      </body>
      </html>
    `
    
    // 下载为.docx文件
    downloadAsDocx(fullHtml, filename)
    
  } catch (error) {
    console.error('转换Word文档失败:', error)
    throw new Error('转换Word文档失败')
  }
}

// 解析markdown内容
const parseMarkdownContent = (markdown: string) => {
  const sections: any = {}
  
  // 提取总体质检情况
  const overallMatch = markdown.match(/一、总体质检情况\s*\n(.*?)(?=\n\n---|\n\n二、|$)/s)
  if (overallMatch) {
    sections.overall = overallMatch[1].trim()
  }
  
  // 提取服务问题分类统计
  const statsMatch = markdown.match(/二、服务问题分类统计\s*\n(.*?)(?=\n\n---|\n\n三、|$)/s)
  if (statsMatch) {
    sections.statistics = statsMatch[1].trim()
  }
  
  // 提取典型案例分析
  const casesMatch = markdown.match(/三、典型案例分析\s*\n(.*?)(?=\n\n---|\n\n四、|$)/s)
  if (casesMatch) {
    sections.cases = casesMatch[1].trim()
  }
  
  // 提取改进建议
  const suggestionsMatch = markdown.match(/四、改进建议\s*\n(.*?)(?=\n\n---|\n\n五、|$)/s)
  if (suggestionsMatch) {
    sections.suggestions = suggestionsMatch[1].trim()
  }
  

  
  return sections
}

// 生成Word文档的HTML内容
const generateWordHtml = (sections: any): string => {
  let html = ''
  
  // 添加标题
  html += '<h1>质检报告</h1>'
  
  // 左列内容
  html += '<div class="left-column">'
  
  // 添加总体质检情况
  if (sections.overall) {
    html += '<div class="section">'
    html += '<h2>一、总体质检情况</h2>'
    html += formatMarkdownText(sections.overall)
    html += '</div>'
  }
  
  // 添加服务问题分类统计
  if (sections.statistics) {
    html += '<div class="section">'
    html += '<h2>二、服务问题分类统计</h2>'
    html += '<p>督办内容关键词发生频次:</p>'
    html += formatMarkdownText(sections.statistics)
    html += '</div>'
  }
  
  // 添加典型案例分析
  if (sections.cases) {
    html += '<div class="section">'
    html += '<h2>三、典型案例分析</h2>'
    html += formatMarkdownText(sections.cases)
    html += '</div>'
  }
  
  html += '</div>'
  
  // 右列内容
  html += '<div class="right-column">'
  
  // 添加改进建议
  if (sections.suggestions) {
    html += '<div class="section">'
    html += '<h2>四、改进建议</h2>'
    html += formatMarkdownText(sections.suggestions)
    html += '</div>'
  }
  

  
  // 添加免责声明
  html += '<div style="margin-top: 50px; text-align: right; font-size: 10pt; color: #666;">'
  html += '<p>以上内容由光明大模型人工智能生成合成</p>'
  html += '</div>'
  
  html += '</div>'
  
  // 清除浮动
  html += '<div class="clear-float"></div>'
  
  return html
}

// 格式化markdown文本为HTML
const formatMarkdownText = (text: string): string => {
  let html = text
  
  // 处理表格
  const tableRows: string[] = []
  let isInTable = false
  
  html = html.replace(/\|(.+)\|/g, (match, content) => {
    const cells = content.split('|').map((cell: string) => cell.trim())
    
    // 跳过分隔行
    if (match.includes('---')) {
      return ''
    }
    
    const cellHtml = cells.map((cell: string) => {
      if (cell.includes('**')) {
        // 处理粗体文本
        const boldText = cell.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        return `<td style="border: 1pt solid #000000; padding: 6pt; text-align: left;">${boldText}</td>`
      }
      return `<td style="border: 1pt solid #000000; padding: 6pt; text-align: left;">${cell}</td>`
    }).join('')
    
    tableRows.push(`<tr>${cellHtml}</tr>`)
    isInTable = true
    
    return `[TABLE_ROW_${tableRows.length - 1}]`
  })
  
  // 处理粗体文本
  html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
  
  // 处理换行
  html = html.replace(/\n/g, '<br>')
  
  // 重新构建表格
  if (isInTable) {
    let tableIndex = 0
    html = html.replace(/\[TABLE_ROW_\d+\]/g, () => {
      if (tableIndex === 0) {
        let tableHtml = '<table style="border-collapse: collapse; width: 100%; margin: 10pt 0; font-size: 10pt;">'
        tableRows.forEach(row => {
          tableHtml += row
        })
        tableHtml += '</table>'
        tableIndex++
        return tableHtml
      }
      return ''
    })
  }
  
  return html
}

// 下载为.docx文件
const downloadAsDocx = (htmlContent: string, filename: string) => {
  // 创建包含Word特定XML的文档
  const docContent = `
    <html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'>
    <head>
      <meta charset="utf-8">
      <title>${filename}</title>
      <!--[if gte mso 9]>
      <xml>
        <w:WordDocument>
          <w:View>Print</w:View>
          <w:Zoom>90</w:Zoom>
          <w:DoNotPromptForConvert/>
          <w:DoNotShowRevisions/>
          <w:DoNotPrintRevisions/>
          <w:DisplayHorizontalDrawingGridEvery>0</w:DisplayHorizontalDrawingGridEvery>
          <w:DisplayVerticalDrawingGridEvery>2</w:DisplayVerticalDrawingGridEvery>
          <w:UseMarginsForDrawingGridOrigin/>
          <w:ValidateAgainstSchemas/>
          <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid>
          <w:IgnoreMixedContent>false</w:IgnoreMixedContent>
          <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText>
          <w:Compatibility>
            <w:BreakWrappedTables/>
            <w:SnapToGridInCell/>
            <w:WrapTextWithPunct/>
            <w:UseAsianBreakRules/>
            <w:DontGrowAutofit/>
          </w:Compatibility>
        </w:WordDocument>
      </xml>
      <![endif]-->
    </head>
    <body>
      ${htmlContent}
    </body>
    </html>
  `
  
  // 创建blob并下载
  const blob = new Blob([docContent], { 
    type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8' 
  })
  
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `${filename}.docx`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  window.URL.revokeObjectURL(url)
}
</script>